package com.ysmygx.cosumer;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ysmygx.constants.AuthConstants;
import com.ysmygx.dto.QueryPayStatusDTO;
import com.ysmygx.entity.AccountTransHisResp;
import com.ysmygx.entity.SingleTransferReq;
import com.ysmygx.entity.SingleTransferResp;
import com.ysmygx.manage.BankManage;
import com.ysmygx.mapper.BizTransferMapper;
import com.ysmygx.utils.BusinessException;
import com.ysmygx.utils.R;
import com.ysmygx.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author laoyanbin
 */
@Slf4j
@Service
@RocketMQMessageListener(topic = "single-transfer-topic", consumerGroup = "single_transfer_consumer")
public class SingleTransferConsumer implements RocketMQListener<String> {

    @Resource
    private BankManage bankManage;
    @Resource
    private BizTransferMapper bizTransferMapper;
    @Autowired
    private TaskExecutor taskExecutor;

    @Value("${ysmygx.cloud.singleTransferUrl}")
    private String singleTransferUrl;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void onMessage(String message) {

        ThreadLocalUtil.set(UUID.fastUUID().toString(true));
        log.info("链路{},接收到单笔转账MQ消息：{}",ThreadLocalUtil.get(), message);
        SingleTransferResp singleTransferResp;
        JSONObject body;
        try {
            //解析参数
            body = JSONUtil.parseObj(message).getJSONObject("body");
            SingleTransferReq transferReq = JSONUtil.toBean(body.getStr("singleTransferReq"), SingleTransferReq.class);

            //更新发送状态
            int updateRow = bizTransferMapper.updateBizTransferByOrderFlowNo(transferReq.getOrderFlowNo());
            if (updateRow <= 0) {
                log.info("链路：{},无此订单或该笔订单重复发送：{}",ThreadLocalUtil.get(),transferReq.getOrderFlowNo());
                return;
            }

            //发送请求
            singleTransferResp = bankManage.singleTransfer(transferReq);
        }catch (Exception e){
            log.error("链路：{},单笔转账消息消费异常",ThreadLocalUtil.get(),e);
            throw new BusinessException(e.getMessage());
        }

        //把支付结果发送服务器处理（异步处理）
        taskExecutor.execute(() -> {
            sendFallBack(body,singleTransferResp,ThreadLocalUtil.get());
        });

    }

    public void sendFallBack(JSONObject body ,SingleTransferResp singleTransferResp,String threadLocalNo) {
        try {
            //等待2秒
            Thread.sleep(2000L);

            QueryPayStatusDTO dto = JSONUtil.toBean(body.getStr("queryPayStatusDTO"), QueryPayStatusDTO.class);
            dto.setOrderStatus(singleTransferResp.getOrderState());
            dto.setOrderMessage(singleTransferResp.getOrderMessage());
            dto.setHostFlowNo(singleTransferResp.getHostFlowNo());

            //调用回调接口，把支付结果发送到服务器
            HttpResponse httpResponse = HttpRequest.post(singleTransferUrl).header("appid", AuthConstants.APPID).body(JSONUtil.toJsonStr(dto)).execute();
            if (!httpResponse.isOk() || JSONUtil.parseObj(httpResponse.body()).getInt("code")!=200){
                log.error("链路：{},单笔转账回调失败:{}",threadLocalNo, httpResponse.body());
            }
        }catch (Exception e) {
            log.error("链路：{},发送单笔转账成功，但回调异常",threadLocalNo,e);
        }
    }

}






